import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage, ElLoading } from "element-plus";

// 定义响应数据类型
interface ResponseData<T = any> {
  code: number;
  data: T;
  msg: string;
}

class Request {
  private instance: AxiosInstance;
  private loadingInstance: ReturnType<typeof ElLoading.service> | null = null;

  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    this.setupInterceptors();
  }

  // 拦截器配置
  private setupInterceptors() {
    // 请求拦截
    this.instance.interceptors.request.use(
      (config) => {
        this.loadingInstance = ElLoading.service({ fullscreen: true });
        const token = localStorage.getItem("token");
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => {
        this.loadingInstance?.close();
        return Promise.reject(error);
      }
    );

    // 响应拦截
    this.instance.interceptors.response.use(
      (response: AxiosResponse<ResponseData>) => {
        this.loadingInstance?.close();
        const { code, data, msg } = response.data;
        if (code === 200) {
          return data; // 直接返回业务数据
        } else if (code == undefined) {
          return response.data; // 直接返回业务数据
        } else if (code === 501) {
          ElMessage({
            showClose: true,
            message: data,
            type: "warning",
          });
        } else {
          ElMessage.error(msg || "请求失败");
          return Promise.reject(msg);
        }
      },
      (error) => {
        this.loadingInstance?.close();
        this.handleError(error);
        return Promise.reject(error);
      }
    );
  }

  // 错误处理
  private handleError(error: any) {
    let errorMessage = "请求异常";
    if (error.response) {
      switch (error.response.status) {
        case 401:
          errorMessage = "登录过期，请重新登录";
          window.location.href = "/login";
          break;
        case 404:
          errorMessage = "接口不存在";
          break;
        case 500:
          errorMessage = "服务器错误";
          break;
      }
    } else if (error.message.includes("timeout")) {
      errorMessage = "请求超时";
    }
    ElMessage.error(errorMessage);
  }

  // 封装请求方法
  public request<T>(config: AxiosRequestConfig): Promise<T> {
    return this.instance.request(config);
  }

  public get<T>(url: string, params?: any): Promise<T> {
    return this.request({ url, method: "GET", params });
  }

  public post<T>(url: string, data?: any): Promise<T> {
    return this.request({ url, method: "POST", data });
  }

  // 其他方法（PUT/DELETE等）
}

// 实例化（支持多环境配置）
const service = new Request({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 10000,
  headers: { "Content-Type": "application/json" },
});

export default service;
